package com.pillar.game;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public final class NodeStatus {
    /**
     * 会话容器
     */
    private static final ConcurrentMap<String, Channel> CHANNEL_MAP = new ConcurrentHashMap<>();
    /**
     * 终端唯一标记
     */
    private static final AttributeKey<String> CLIENT_ID = AttributeKey.newInstance("client_id");

    /**
     * 保存会话
     *
     * @param channel
     * @param clientId
     */
    public static void addChannel(Channel channel, String clientId) {
        if (null != clientId) {
            CHANNEL_MAP.put(clientId, channel);
        }
    }

    /**
     * 移除会话
     *
     * @param channel
     */
    public static void removeChannel(Channel channel) {
        Attribute<String> clientKey = channel.attr(CLIENT_ID);
        if (null != clientKey && null != clientKey.get()) {
            CHANNEL_MAP.remove(clientKey.get());
        }
        channel.close();
    }

    /**
     * 查询会话
     *
     * @param clientId
     * @return
     */
    public static Channel findChannel(String clientId) {
        if (null != clientId) {
            return CHANNEL_MAP.get(clientId);
        }
        return null;
    }

    /**
     * 广播
     *
     * @param tws
     */
    public static void send2All(TextWebSocketFrame tws) {
        CHANNEL_MAP.keySet().forEach(k -> {
            CHANNEL_MAP.get(k).writeAndFlush(tws);
        });
    }
}
